package cn.gailvlun.gll.net.token;

import android.support.annotation.Nullable;
import android.util.Log;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import retrofit2.CallAdapter;
import retrofit2.Retrofit;



public class CustomFactory extends CallAdapter.Factory {

    public static CustomFactory create(Map<Integer, String> authInfos) {
        Log.d("callAdapter", "create");
        return new CustomFactory(authInfos);
    }

    private Map<Integer, String> mAuthInfos;

    public CustomFactory(Map<Integer, String> authInfos) {
        Log.d("callAdapter", "Constructor");

        mAuthInfos = authInfos;
    }

    @Nullable
    @Override
    public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
        Log.d("callAdapter", "get: ");
        Authorization authorization = getAnnotation(annotations);
        List<CallAdapter.Factory> factories = retrofit.callAdapterFactories();
        for (int i = 0; i < factories.size(); i++) {
            if (!(factories.get(i) instanceof CustomFactory)) {
                CallAdapter adapter = factories.get(i).get(returnType, annotations, retrofit);
                if (adapter != null) {
                    if (authorization != null) {
                        return new CustomAdapter(adapter, mAuthInfos);
                    }
                    return adapter;
                }
            }
        }
        return null;
    }

    private Authorization getAnnotation(Annotation[] annotations) {
        for (Annotation annotation:
             annotations) {
            if (Authorization.class == annotation.annotationType()) {
                return (Authorization) annotation;
            }
        }
        return null;
    }
}
